<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<html>
<head>
    <title>业务表管理</title>
    <meta name="decorator" content="default"/>
    <script type="text/javascript">
        function changeCheck(_node,allFlag) {
            if(allFlag){
                if ($(_node).prop("checked")) {
                    $("#contentTbody input[type='checkbox'].selectItem").prop("checked", "checked");
                } else {
                    $("#contentTbody input[type='checkbox'].selectItem").removeAttr("checked");
                }
            }
        }

        $(document).ready(function () {
            $("#comments").focus();
            $("#inputForm").validate({
                submitHandler: function (form) {
                    loading('正在提交，请稍等...');
                    $("input[type=checkbox]").each(function () {
                        $(this).after("<input type=\"hidden\" name=\"" + $(this).attr("name") + "\" value=\""
                            + ($(this).attr("checked") ? "1" : "0") + "\"/>");
                        $(this).attr("name", "_" + $(this).attr("name"));
                    });
                    form.submit();
                },
                errorContainer: "#messageBox",
                errorPlacement: function (error, element) {
                    $("#messageBox").text("输入有误，请先更正。");
                    if (element.is(":checkbox") || element.is(":radio") || element.parent().is(".input-append")) {
                        error.appendTo(element.parent().parent());
                    } else {
                        error.insertAfter(element);
                    }
                }
            });

            $("#primaryTableName").change(function (e) {
                var primaryTableName = $(this).val();
                console.info(primaryTableName);
                $.ajax({
                    url: '${ctx}/gen/genJoinColumn/ajaxPrimaryTableColumn',
                    type: 'post',
                    data: {primaryTableName: primaryTableName},
                    dataType: 'json',
                    success: function (data) {
                        if (data && data.length > 0) {
                            $('#primaryKey').empty();
                            $('#primaryKey').append('<option value="" id="default_primaryKey">请选择</option>');
                            var selected = null;

                            $('#contentTbody').empty();
                            for (var i = 0; i < data.length; i++) {
                                var column = data[i];

                                if (i == 0 || data[i].name == 'id') {
                                    selected = data[i].name;
                                }
                                $('#primaryKey').append('<option value="' + data[i].name + '">' + data[i].name + '</option>');

                                var html = [
                                    '<tr id='+column.name+'>',
                                        '<td>',
                                            '<input type="checkbox" class="selectItem" name="columnId" value="'+column.name+'"/>',
                                        '</td>',
                                        '<td nowrap>',
                                            '<input type="hidden" name="id" value="'+column.id+'"/>',
                                            '<input type="hidden" name="delFlag" value="'+column.delFlag+'"/>',
                                            '<input type="hidden" name="genTable.id" value="'+column.genTable.id+'"/>',
                                            '<input type="hidden" name="name" value="'+column.name+'"/>'+column.name,
                                        '</td>',
                                        '<td>',
                                            '<input type="text" name="aliasName" value="'+column.name +'" maxlength="200" class="required" style="width:100px;"/>',
                                        '</td>',
                                        '<td>',
                                            '<input type="text" name="comments" value="'+column.comments +'" maxlength="200" class="required" style="width:100px;"/>',
                                        '</td>',
                                        '<td>',
                                            '<input type="hidden" name="jdbcType" value="'+column.jdbcType +'"/>'+column.jdbcType,
                                        '</td>',
                                        '<td>',
                                            '<select name="javaType" class="required input-mini" style="width:85px;*width:75px">',
                                                '<c:forEach items="${config.javaTypeList}" var="dict">',
                                                '<option value="${dict.value}" ${dict.value==''?'selected':''} title="${dict.description}">${dict.label}</option>',
                                                '</c:forEach>',
                                            '</select>',
                                        '</td>',
                                        '<td>',
                                            '<input type="text" name="javaField" value="'+column.javaField +'" maxlength="200" class="required" style="width:100px;"/>',
                                        '</td>',
                                        '<td>',
                                            '<input type="checkbox" name="isList" value="1" '+(column.isList=='1'?'checked':'') +'/>',
                                        '</td>',
                                        '<td>',
                                            '<input type="checkbox" name="isQuery" value="1" '+(column.isQuery=='1'?'checked':'') +'/>',
                                        '</td>',
                                        '<td>',
                                            '<select name="queryType" class="required input-mini">',
                                                '<c:forEach items="${config.queryTypeList}" var="dict">',
                                                '<option value="${fns:escapeHtml(dict.value)}" ${fns:escapeHtml(dict.value)==''?'selected':''} title="${dict.description}">${fns:escapeHtml(dict.label)}</option>',
                                                '</c:forEach>',
                                            '</select>',
                                        '</td>',
                                        '<td>',
                                            '<select name="showType" class="required" style="width:100px;">',
                                                '<c:forEach items="${config.showTypeList}" var="dict">',
                                                '<option value="${dict.value}" ${dict.value==''?'selected':''} title="${dict.description}">${dict.label}</option>',
                                                '</c:forEach>',
                                            '</select>',
                                        '</td>',
                                        '<td>',
                                            '<input type="text" name="dictType" value="'+column.dictType +'" maxlength="200" class="required" style="width:100px;"/>',
                                        '</td>',
                                        '<td>',
                                            '<select name="validate" style="width:100px;">',
                                                '<option value="">请选择</option>',
                                                '<c:forEach items="${config.validateList}" var="dict">',
                                                    '<option value="${dict.value}" ${dict.value==''?'selected':''} title="${dict.description}">${dict.label}</option>',
                                                '</c:forEach>',
                                            '</select>',
                                        '</td>',
                                    '</tr>'
                                ];

                                $('#contentTbody').append(html.join(''));
                            }
                            $('#primaryKey').select2('val', selected);
                        }
                    }
                });
            });
        });

        function save(){
            var checkeds = $("#contentTbody input[type='checkbox'].selectItem:checked");
            //if (checkeds.length == 0) {
            //    alert("请选择要关联的字段");
            //    return;
            //}
            var genTableJoinColumns = new Array();
            for (var i = 0; i < checkeds.length; i++) {
                var columnName = $(checkeds[i]).val();
                var item = formParams(columnName);
                genTableJoinColumns[i]=item;
            }
            console.info(genTableJoinColumns);

            var id = $('#id').val();
            var primaryTableName = $('#primaryTableName').val();
            var primaryKey = $('#primaryKey').val();
            var joinType = $('#joinType').val();
            var params = {
                genTableColumn: {
                    id : id,
                    primaryTableName : primaryTableName,
                    primaryKey : primaryKey,
                    joinType : joinType
                },
                genTableJoinColumns :genTableJoinColumns
            };
            $.ajax({
                url: '${ctx}/gen/genJoinColumn/save',
                type: 'post',
                data:JSON.stringify(params) ,
                dataType: 'json',
                contentType:"application/json",
                success: function (data) {
                    console.info(data);
                    if(data || data=='true'){
                        alert('设置成功');
                    }else{
                        alert('设置失败!!!');
                    }
                }
            });

            return false;
        }



        function formParams(formId) {
            var nodes = $("#contentTable #" + formId).find("input[type='text'],input[type='password'],input[type='hidden'],input[type='email'],input[type='url']," +
                "input[type='number'],input[type='tel'],input[type='radio']:checked," +
                "input[type='range'],input[type='search'],input[type='color']," +
                "input[type='checkbox']:checked,textarea,select,img");
            var params = {};
            for (var i = 0; i < nodes.length; i++) {
                var e = $(nodes[i]);
                var name = e.attr("name");
                if (name == undefined) continue;
                if (params[name] == undefined) {
                    params[name] = e.val()||e.attr("value");
                } else {
                    params[name] += "|" + (e.val()||e.attr("value"));
                }
            }
            return params;
        }
    </script>
</head>
<body>
<form:form id="inputForm" modelAttribute="genTableColumn" action="${ctx}/gen/genJoinColumn/form" method="post" class="form-horizontal">
    <sys:message content="${message}"/>
    <br/>

    <fieldset>
        <legend>基本信息</legend>
        <div class="control-group">
            <label class="control-label">字段名称:</label>
            <div class="controls">
                <form:hidden path="id" htmlEscape="false" readonly="true"/>
                <form:input path="name" htmlEscape="false" maxlength="200" class="required" readonly="true"/>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">主表名称:</label>
            <div class="controls">
                <form:select path="primaryTableName" cssClass="input-xlarge" id="primaryTableName">
                    <form:option value="">无</form:option>
                    <form:options items="${tableList}" itemLabel="nameAndComments" itemValue="name" htmlEscape="false"/>
                </form:select>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">主表主键:</label>
            <div class="controls">
                <select id="primaryKey" name="primaryKey" cssClass="input-xlarge" style="width:300px;">
                    <option value="" id="default_primaryKey">请选择</option>
                    <c:if test="${not empty genTableColumn.primaryKey}">
                    <option value="${genTableColumn.primaryKey}" selected>${genTableColumn.primaryKey}</option>
                    </c:if>
                </select>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label">连接类型:</label>
            <div class="controls">
                <select id="joinType" name="joinType" cssClass="input-xlarge">
                    <option value="LEFT" ${genTableColumn.joinType=='LEFT'?'selected="selected"':''}>左连接</option>
                    <option value="INNER" ${genTableColumn.joinType=='INNER'?'selected="selected"':''}>内连接</option>
                    <option value="RIGHT" ${genTableColumn.joinType=='RIGHT'?'selected="selected"':''}>右连接</option>
                    <option value="FULL" ${genTableColumn.joinType=='FULL'?'selected="selected"':''}>完全连接</option>
                </select>
            </div>
        </div>
        <legend>字段列表</legend>
        <div class="control-group">
            <table id="contentTable" class="table table-striped table-bordered table-condensed">
                <thead>
                <tr>
                    <th><input id="selectAll" name="" type="checkbox" value="" class="cbox" onclick="changeCheck(this,true)"/></th>
                    <th title="数据库字段名">列名</th>
                    <th title="数据库字段别名">别名</th>
                    <th title="默认读取数据库字段备注">说明</th>
                    <th title="数据库中设置的字段类型及长度">物理类型</th>
                    <th title="实体对象的属性字段类型">Java类型</th>
                    <th title="实体对象的属性字段（对象名.属性名|属性名2|属性名3，例如：用户user.id|name|loginName，属性名2和属性名3为Join时关联查询的字段）">Java属性名称 <i class="icon-question-sign"></i></th>
                    <th title="选中后该字段被加入到查询列表里">列表</th>
                    <th title="选中后该字段被加入到查询条件里">查询</th>
                    <th title="该字段为查询字段时的查询匹配放松">查询匹配方式</th>
                    <th title="字段在表单中显示的类型">显示表单类型</th>
                    <th title="显示表单类型设置为“下拉框、复选框、点选框”时，需设置字典的类型">字典类型</th>
                    <th title="">校验类型</th>
                </tr>
                </thead>
                <tbody id="contentTbody">
                    <c:forEach items="${columns}" var="column">
                        <tr id="${column.name}">
                            <td>
                                <input type="checkbox" class="selectItem" name="columnId" value="${column.name}" ${column.checked?'checked':''}/>
                            </td>
                            <td nowrap>
                                <input type="hidden" name="id" value="${column.id}"/>
                                <input type="hidden" name="delFlag" value="${column.delFlag}"/>
                                <input type="hidden" name="genTable.id" value="${column.genTable.id}"/>
                                <input type="hidden" name="name" value="${column.name}"/>${column.name}
                            </td>
                            <td>
                                <input type="text" name="aliasName" value="${column.aliasName}" maxlength="200" class="required" style="width:100px;"/>
                            </td>
                            <td>
                                <input type="text" name="comments" value="${column.comments}" maxlength="200" class="required" style="width:100px;"/>
                            </td>
                            <td>
                                <input type="hidden" name="jdbcType" value="${column.jdbcType}"/>${column.jdbcType}
                            </td>
                            <td>
                                <select name="javaType" class="required input-mini" style="width:85px;*width:75px">
                                    <c:forEach items="${config.javaTypeList}" var="dict">
                                        <option value="${dict.value}" ${dict.value==''?'selected':''} title="${dict.description}">${dict.label}</option>
                                    </c:forEach>
                                </select>
                            </td>
                            <td>
                                <input type="text" name="javaField" value="${column.javaField}" maxlength="200" class="required" style="width:100px;"/>
                            </td>
                            <td>
                                <input type="checkbox" name="isList" value="1" ${column.isList==1?'checked':''} />
                            </td>
                            <td>
                                <input type="checkbox" name="isQuery" value="1" ${column.isList==1?'checked':''}/>
                            </td>
                            <td>
                                <select name="queryType" class="required input-mini">
                                    <c:forEach items="${config.queryTypeList}" var="dict">
                                        <option value="${fns:escapeHtml(dict.value)}" ${fns:escapeHtml(dict.value)==''?'selected':''} title="${dict.description}">${fns:escapeHtml(dict.label)}</option>
                                    </c:forEach>
                                </select>
                            </td>
                            <td>
                                <select name="showType" class="required" style="width:100px;">
                                    <c:forEach items="${config.showTypeList}" var="dict">
                                        <option value="${dict.value}" ${dict.value==''?'selected':''} title="${dict.description}">${dict.label}</option>
                                    </c:forEach>
                                </select>
                            </td>
                            <td>
                                <input type="text" name="dictType" value="${column.dictType}" maxlength="200" class="required" style="width:100px;"/>
                            </td>
                            <td>
                                <select name="validate" style="width:100px;">
                                    <option value="">请选择</option>
                                    <c:forEach items="${config.validateList}" var="dict">
                                        <option value="${dict.value}" ${dict.value==column.validate?'selected':''} title="${dict.description}">${dict.label}</option>
                                    </c:forEach>
                                </select>
                            </td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </fieldset>
</form:form>
<div class="form-actions">
    <shiro:hasPermission name="gen:genTable:edit"><input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存" onclick="save();"/>&nbsp;</shiro:hasPermission>
    <input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
</div>
</body>
</html>
